package com.hou.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hou.oss.service.OssService;
import com.hou.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author shkstart
 * @create 2021-10-11-21:24
 */
@Service
public class OssServiceImpl implements OssService {

    // 上传文件到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {


        String endpoint = ConstantPropertiesUtils.END_POIND;

        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String buckteName = ConstantPropertiesUtils.BUCKET_NAME;

        try {

            // 创建oss实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");

            // 唯一文件名
            fileName  = uuid + fileName;

            // 获取当前日期
            String date = new DateTime().toString("yyyy/MM/dd");

            // 上传文件路径
            fileName = date + "/" + fileName;

            // 文件上传
            ossClient.putObject(buckteName, fileName, inputStream);

            ossClient.shutdown();

            //文件路径拼接
            String url = "https://"+buckteName+"."+endpoint+"/"+fileName;
            return url;

        } catch (Exception e){
            return null;
        }
    }
}
